<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品名称" prop="goodsName">
        <el-input
          v-model="queryParams.goodsName"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    
    <el-table v-loading="loading" :data="shoppingCartItemList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />

      <el-table-column label="图片" align="center" prop="goodsCoverImg" width="150px" fixed class="el-image-viewer_wrapper">
        <template #default="scope">
          <el-image
              style="width: 100px; height: 100px"
              :key="scope.row.id"
              :src="scope.row.goodsCoverImg"
              :preview-teleported="true"
              :preview-src-list="[scope.row.goodsCoverImg]">
          </el-image>
        </template>
      </el-table-column>

      <el-table-column label="商户名称" align="center" prop="goodsName" />
      <el-table-column label="规格" align="center" prop="goodsSpecs" />
      <el-table-column label="单价" align="center" prop="goodsPrice" />
      <el-table-column label="数量" align="center" prop="goodsCount">
        <template #default="scope">
          <el-input-number style="margin-left: 20px" v-model="scope.row.goodsCount" @change="handleChange(scope.row.goodsCount, scope.row)" :min="1" label="数量"></el-input-number>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" @click="handleDelete(scope.row)" v-hasPermi="['business:shoppingCartItem:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-row :gutter="10" class="mb8">
      <el-col :span="22">
<!--        商品总额： {{ cost.totalAmount }} 元，运费：{{ cost.shippingFee }} 元，实付款：{{ cost.disbursements }} 元-->
        商品总额： {{ totalAmount }} 元，运费：{{ shippingFee }} 元，实付款：{{ disbursements }} 元
      </el-col>
      <el-col :span="2">
        <el-button type="primary" plain @click="handleSaveOrder" >提交订单</el-button>
      </el-col>
    </el-row>
    
    <!-- <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    /> -->


    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="merchantInvoiceRef" :model="form" :rules="rules" label-width="100px">

        <el-form-item label="订单店铺" prop="merchantShopId">
          <template #default="scope">
            <el-select v-model="form.merchantShopId" size="small" style="width: 300px; margin-right: 10px" filterable clearable @change="shopChange(form.merchantShopId)">
              <el-option v-for="item in shopArr" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </template>
        </el-form-item>

        <el-form-item label="收货地址" prop="addressId">
          <template #default="scope">
            <el-select v-model="form.addressId" size="small" style="width: 300px; margin-right: 10px" filterable clearable @change="addressChange(form.addressId)">
              <el-option v-for="item in addressArr" :key="item.id" :label="item.addressNameStr" :value="item.id" />
            </el-select>
          </template>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitSaveOrder">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ShoppingCartItem">
import { listShoppingCartItem, getShoppingCartItem, delShoppingCartItem, addShoppingCartItem, updateShoppingCartItem,
  saveOrder, listMerchantShopInfo, listMerchantAddressInfo, updateShoppingCartItemNum, getOrderAmountDetail } from "@/api/business/shoppingCartItem";

const { proxy } = getCurrentInstance();

const shoppingCartItemList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const shopArr = ref([]);//商铺list
const addressArr = ref([]);//商铺list
const selRows = reactive([]);//选中的行
// const cost = reactive({
//   totalAmount: 0, //商品总额
//   shippingFee: 0, //运费
//   disbursements: 0, //实付款
// })
const totalAmount = ref(0);
const shippingFee = ref(0);
const disbursements = ref(0);

const data = reactive({
  form: {
    merchantShopId : null,
    addressId: null
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    goodsName: null
  },
  rules: {
  },

  saveOrderParams: {
    cartItemIdStrList: null,
    merchantShopId : null,
    addressId: null
  },

  searchParams: {
    id: null,
    num: null
  },
});

const { queryParams, form, rules, saveOrderParams, searchParams } = toRefs(data);

/** 查询购物车信息列表 */
function getList() {
  loading.value = true;
  listShoppingCartItem(queryParams.value).then(response => {
    shoppingCartItemList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    merchantId: null,
    userId: null,
    goodsId: null,
    goodsCount: null,
    delFlag: null,
    createTime: null,
    updateTime: null
  };
  proxy.resetForm("shoppingCartItemRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
  selRows.length = 0;
  selRows.push(...selection);
  calculatePrice()
}

/** 计算：商品总额，运费，实付款 */
function calculatePrice() {

  const _id = ids.value

  if(_id != null && _id != ''){
    getOrderAmountDetail(_id).then(response => {

      totalAmount.value = response.data.totalAmount;
      shippingFee.value = response.data.shippingFee;
      disbursements.value = response.data.disbursements;
    });
  }


}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加购物车信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getShoppingCartItem(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改购物车信息";
  });
}

/** 提交订单 */
function handleSaveOrder(row) {
  const _ids = row.id || ids.value;
  let cartItemIdStrList = '';
  for (let i = _ids.length - 1; i >= 0; i--) {
    cartItemIdStrList = cartItemIdStrList + _ids[i] + ',';
  }
  saveOrderParams.value.cartItemIdStrList = cartItemIdStrList;

  open.value = true;
  //清空弹窗中的信息
  form.value.addressId = null;
  form.value.merchantShopId = null
  title.value = "提交订单信息";

  //查询店铺信息
  getMerchantShopList();
  //查询收货地址信息
  getMerchantAdderssList();
}

/** 提交订单 */
function submitSaveOrder() {

  // saveOrderParams.value.addressId = name;
  let addressId =saveOrderParams.value.addressId;
  let merchantShopId =saveOrderParams.value.merchantShopId;
  if(addressId == null || addressId =='' || addressId == undefined ||
      merchantShopId == null || merchantShopId =='' || merchantShopId == undefined ){
    return proxy.$modal.msgError("收货地址、订单店铺必选！");
  }

  proxy.$modal.confirm('是否确认提交订单？').then(function() {
    return saveOrder(saveOrderParams.value);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("提交成功");
    open.value = false;
  }).catch(() => {});
}


/** 提交按钮 */
function submitForm() {
  proxy.$refs["shoppingCartItemRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateShoppingCartItem(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addShoppingCartItem(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除购物车？').then(function() {
    return delShoppingCartItem(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('business/shoppingCartItem/export', {
    ...queryParams.value
  }, `shoppingCartItem_${new Date().getTime()}.xlsx`)
}

/** 查询商户信息列表 */
function getMerchantShopList() {
  listMerchantShopInfo().then(response => {
    shopArr.value = response.rows;
  });
}

function shopChange(name){
  console.log("--------"+ name)
  saveOrderParams.value.merchantShopId = name;
}

/** 查询地址信息列表 */
function getMerchantAdderssList() {
  listMerchantAddressInfo().then(response => {
    addressArr.value = response.rows;
  });
}

function addressChange(name){
  console.log("++++"+ name)
  saveOrderParams.value.addressId = name;
}

async function handleChange(goodsCount,row) {
  console.log("----goodsCount-" + goodsCount)
  console.log("----row-" + row)
  // updateNum(row.id, goodsCount);

  searchParams.value.id = row.id;
  searchParams.value.num = goodsCount;

  await updateShoppingCartItemNum(searchParams.value);
  if(selRows.length) calculatePrice()
}

function updateNum(id,num){
  console.log("----id-" + id)
  console.log("----num-" + num)

  searchParams.value.id = id;
  searchParams.value.num = num;

  shopCartUpdateNum(searchParams.value)
      .then((response) => {

      })
      .catch(() => {})
}

// function checkChange(){
//   this.totalMoney = 0;
//   this.totalNum = 0;
//   this.isShow = false;
//   for(let i = 0; i < this.list.length; i ++){
//     let json = this.list[i];
//     if (json.checked) {
//       this.isShow = true;
//       this.totalMoney += (Number(json.sellingPrice) * Number(json.goodsCount));
//       this.totalNum += json.goodsCount;
//     }
//   }
//   this.totalMoney = parseFloat(this.totalMoney).toFixed(2);
// }



getList();
</script>
<style lang="scss" scoped>
.mb8{
  align-items: center;
  margin-top: 10px;
  text-align: right;
}

.el-image-viewer_wrapper{
  z-index: 20028 !important;
}
</style>
